package health.lm.com.shop.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.widget.EditText;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jakewharton.rxbinding2.view.RxView;
import com.lm.sjy.titlebar.widget.CommonTitleBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import health.lm.com.component_base.base.mvp.activity.XListActivity;
import health.lm.com.router.ARouterConstant;
import health.lm.com.shop.R;
import health.lm.com.shop.R2;
import health.lm.com.shop.adapter.HLChatAdapter;
import health.lm.com.shop.entity.HLChatEntity;
import health.lm.com.shop.presenter.HLChatPresenter;

/**
 * Created by Android Studio .
 * Project：hlian health.lm.com.shop.activity
 * Date：2019/8/10 8:49
 * Introduce：私信聊天页面
 */
@Route(path = ARouterConstant.HLChatActivity)
public class HLChatActivity extends XListActivity<HLChatPresenter> implements HLChatView {
    private static boolean isStop = false;
    @Autowired
    public String name;
    @Autowired
    public String id;
    @BindView(R2.id.titlebar)
    CommonTitleBar mTitlebar;
    @BindView(R2.id.rv_list)
    RecyclerView mRvList;
    @BindView(R2.id.srl_layout)
    SmartRefreshLayout mSrlLayout;
    @BindView(R2.id.editText)
    EditText mEditText;
    @BindView(R2.id.imageView7)
    ImageView mImageView7;
    @BindView(R2.id.constraintLayout)
    ConstraintLayout mConstraintLayout;
    private HLChatAdapter mChatAdapter;

    /**
     * 加载数据
     *
     * @param isRefresh true 刷新 false 加载更多
     * @param layout    头部布局
     * @param page      页数
     * @param pageSize  每页数量
     */
    @Override
    public void loadListData(boolean isRefresh, Object layout, int page, int pageSize) {
        getP().getData(id);
    }

    @Override
    public int getLayoutId() {
        return R.layout.hl_activity_chat;
    }

    @Override
    public HLChatPresenter newP() {
        return new HLChatPresenter();
    }

    @SuppressLint("CheckResult")
    @Override
    public void initData(Bundle savedInstanceState) {
        if (TextUtils.isEmpty(name)) name = "XXX";
        mTitlebar.getCenterTextView().setText(name);
        mTitlebar.setListener((v, action, extra) -> {
            switch (action) {
                case CommonTitleBar.ACTION_LEFT_BUTTON:
                    finish();
                    break;
                case CommonTitleBar.ACTION_RIGHT_TEXT:
                    ARouter.getInstance().build(ARouterConstant.HLChatRecordActivity)
                            .withString("title",name)
                            .withString("id",id)
                            .navigation();
                    break;
            }
        });

        mChatAdapter = new HLChatAdapter(new ArrayList<>());
        //mRvList.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, true));
        mRvList.setLayoutManager(new LinearLayoutManager(context));
        mRvList.setAdapter(mChatAdapter);

        super.recyclerView = mRvList;
        super.rlRefreshLayout = mSrlLayout;
        super.adapter = mChatAdapter;
        super.initData(savedInstanceState);
        RxView.clicks(mImageView7).throttleFirst(1, TimeUnit.SECONDS).subscribe(v -> {
            String word = mEditText.getText().toString();
            if (TextUtils.isEmpty(word)) return;
            getP().submitContetn(id, word);
            mEditText.setText("");
        });

        //轮询查询 刷新聊天最新数据
        Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (isStop) return;
                getP().getData(id);
                handler.postDelayed(this, 3000);
            }
        };
        handler.postDelayed(runnable, 1000);
    }

    @Override
    public void setNewData(List<HLChatEntity> pNewData) {
        if (isRefresh) {
            mSrlLayout.finishRefresh();
            mChatAdapter.setNewData(pNewData);
        } else {
            mChatAdapter.addData(pNewData);
            if (pNewData.size() >= pageSize) mChatAdapter.loadMoreComplete();
            else mChatAdapter.loadMoreEnd();
        }
        //滑动到最底部
        mRvList.scrollToPosition(mChatAdapter.getItemCount() - 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isStop = true;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
}
